<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
<div th:fragment="main" id="apkupdate" class="apkupdate">
    <style>
        html {
            height: 100%;
        }

        body {
            height: 100%;
            overflow: hidden;
        }

        #apkupdate {
            width: auto;
            padding: 20px 25px 0 25px;
            height: calc(100vh - 50px);
            overflow: hidden;
        }

        .content-title {
            color: #333;
            font-size: 14px;
            padding-bottom: 30px;
        }

        .content-title span {
            cursor: pointer;
        }

        .main .user-add {
            padding: 40px 0 20px;
            background-color: #FFF;
        }

        #fileupload {
            display: none;
        }

        .settings {
            margin-top: 50px;
        }

        .upfile {
            font-size: 12px;
        }

        .uploadIcon {
            height: 18px;
            width: 18px;
        }

        .upfile a {
            color: #7dc196;
        }

        .form-group {
            margin-bottom: 26px;
        }
        .btn-bg {
            margin: 0 10px;
            padding: 7px 25px;
        }
        .btn-cyan {
            color: #fff;
            background-color: rgba(26, 156, 178, 1);
            border-color: rgba(26, 156, 178, 1);
        }

        .btn {
            border-radius: 0;
        }
        .footer {
            text-align: right;
            margin-right: 20%;
        }
    </style>

    <!-- 面包屑 -->
    <div class="content-title">
        <p><span>系统设置</span>&nbsp;>&nbsp;<span>APK 升级</span></p>
    </div>
    <div id="useradd" style="overflow-x:hidden;overflow-y:auto;">
        <!--诉求提交模板-->
        <div class="body application">
            <div class="settings">
                <form action="" class="form-horizontal" id="amend_form">
                    <div class="form-group">
                        <label for="" class="col-xs-3 control-label">android 版本</label>
                        <div class="col-xs-7">
                            <input type="text" name="version" class="form-control input-sm">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="" class="col-xs-3 control-label">版本说明</label>
                        <div class="col-xs-7">
                            <textarea name="descript" rows="15" id="content1" class="form-control input-sm"></textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="" class="col-xs-3 control-label">上传apk</label>
                        <div class="col-xs-7 ckeditor" style="margin-top:7px;">
                            <a type="text" id="btnUpload" onclick="appFile()" style="height:100%;">
                                <span style="color:#0000FF">添加附件</span>
                            </a>
                            <div id="uploads"></div>
                            <input id="fileupload"
                                   accept='.apk'
                                   type="file" name="file"  th:attr="data-url=@{'/file/upload/temp'}">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-xs-10 footer">
                            <a type="text" class="btn btn-cyan btn-bg" id="submitAppeal"
                               style="margin-left: 10px;">提 交</a>
                            <a type="text" class="btn btn-cyan btn-bg" id="reset">重 置</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!--<hr>-->
    <script th:src="@{/assets/jquery/plugins/jquery.ui.widget.js}"></script>
    <script th:src="@{/assets/jquery/plugins/jquery.iframe-transport.js}"></script>
    <script th:src="@{/assets/jquery/plugins/jquery.fileupload.js}" type="text/javascript"></script>
    <script>
        var userid = userid;
        var imagepaths = [];

        //上传附件
        function appFile() {
            var upFiles = $(".upfile");

            //获取选择的 img.attr
            upFiles.each(function (index, element) {
                console.log($(element).attr('attr'));
            });

            if (upFiles.length == 1) {
                toastr.error("只能上传一个 apk ！", "文件上传");
            } else {
                $('#fileupload').click();
            }
        }

        //删除选择的图片
        function deleteImg(obj) {
            var url = $(obj).attr('attr');
            $.ajax({
                type: 'get',
                url: url,
                contentType: "application/json",
                success: function (data) {
                    toastr['success']("成功！", "删除");
                    imagepaths = [];
                    $(obj).parent().parent().remove();
                },
                error: function (error) {
                    toastr['error']("失败！", "加载界面");
                    console.log(error);
                }
            });
        }

        // 附件上传
        $('#fileupload').fileupload({
            singleFileUploads: true,
            dataType: 'json',
            done: function (e, data) {
                console.log(data.result);
                if (data.result.code == 1) {
                    var uploadFiles = data.result.data;
                    uploadFiles.forEach(function (filepath) {
                        var imageStr = "<div class='upfile'><div class='fileName'><i class='fa fa-paperclip uploadIcon'></i>"
                            + filepath.upFileName + "(" + bytesToSize(filepath.fileSize) + ")"
                            + "<a type='text' attr='" + filepath.deletePath
                            + "'class='delfileButton' onclick='deleteImg(this)'>&nbsp;[删除]</a></div></div>";
                        $("#uploads").append(imageStr);
                        imagepaths.push(filepath.serverPath);
                    })
                } else {
                    toastr['error']("失败！", "上传APK失败！");
                }
            }
        });


        //提交
        $("#submitAppeal").on("click", function () {
            imagepath = imagepaths.join(",");
            var images = {};
            images.name = 'filepath';
            images.value = imagepath;
            var formArray = $("#amend_form").serializeArray();
            formArray.push(images);
            if(formArray[0].value.trim().length == 0){
                toastr.error('版本号不能为空！');
                return;
            }
            if(formArray[1].value.trim().length == 0){
                toastr.error('版本描述不能为空！');
                return;
            }
            console.log(formArray);
            if(formArray[2].value.trim().length == 0){
                toastr.error('请上传APK 文件！');
                return;
            }
            var form = arrayToJson(formArray);
            var formData = JSON.stringify(form).replace(/\\\\/g, '/');

            $.ajax({
                url: contextPath + '/apk/upload/',
                type: 'POST',
                data: formData,
                contentType: "application/json",
                success: function (info) {
                    toastr.success('android 新版本上传成功！','提交成功！');
                    $('#amend_form')[0].reset();
                    $('#uploads').children('div').remove();
                    imagepaths = [];
                },
                error: function () {
                    toastr.error("提交失败，请稍后再试！");
                }
            });
        });

        // 将表单数据转化为json格式
        function arrayToJson(formArray) {
            var dataArray = {};
            $.each(formArray, function () {
                if (dataArray[this.name]) {
                    if (!dataArray[this.name].push) {
                        dataArray[this.name] = [dataArray[this.name]];
                    }
                    dataArray[this.name].push(this.value || '');
                } else {
                    dataArray[this.name] = this.value || '';
                }
            });
            return dataArray;
        }

        // 重置
        $('#reset').on('click', function () {
            $('#amend_form')[0].reset();
            $('#uploads').children('div').remove();
            imagepaths = [];
        });

        // 文件大小
        function bytesToSize(bytes) {
            var type = ["byte", "KB", "MB", "GB"];//定义单位数组
            var size = bytes;//原始值，单位为byte
            var i=0;//选用第几个单位
            while(size >= 1024)//当当前值大于等于1024时，即转换到下一位，如此循环。当然也可设置为1000，或者更低
            {
                size = size/1024;//当前值除以1024
                i++;//所选取的单位增加一个
            }
            return newsize = size.toFixed(2) + type[i];//最终结果为最终值加上单位
        }
    </script>
</div>
</body>
</html>